/**
 * 严肃声明：
 * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
 * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
 * Copyright (c) 2021 十三 all rights reserved.
 * 版权所有，侵权必究！
 */
package com.my.bbs.service.impl;

import com.my.bbs.common.Constants;
import com.my.bbs.common.ServiceResultEnum;
import com.my.bbs.dao.MyPostMapper;
import com.my.bbs.dao.MyUserMapper;
import com.my.bbs.entity.MyRole;
import com.my.bbs.entity.MyUser;
import com.my.bbs.service.MyRoleService;
import com.my.bbs.service.MyUserService;
import com.my.bbs.util.MD5Util;
import com.my.bbs.util.PageQueryUtil;
import com.my.bbs.util.PageResult;
import com.my.bbs.util.SystemUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author 86187
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MyUserServiceImpl implements MyUserService {

    @Resource
    private MyUserMapper myUserMapper;

    @Resource
    private MyRoleService roleService;

    @Resource
    private MyPostMapper postMapper;

    @Override
    public String register(String loginName, String password, String nickName, HttpSession session) {
        if (myUserMapper.selectByLoginName(loginName) != null) {
            return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult();
        }
        //注册用户
        MyUser registerUser = new MyUser();
        registerUser.setLoginName(loginName);
        registerUser.setNickName(nickName);
        //角色id
        registerUser.setRoleId(3L);
        //默认头像
        registerUser.setHeadImgUrl("/images/avatar/default.png");
        //默认介绍
        registerUser.setIntroduce("这个人很懒，什么都没留下~");
        //居住地
        registerUser.setLocation("未知");
        registerUser.setGender("未知");
        String passwordMD5 = MD5Util.MD5Encode(password, "UTF-8");
        registerUser.setPasswordMd5(passwordMD5);
        if (myUserMapper.insertSelective(registerUser) > 0) {
            MyUser myUser = myUserMapper.selectByLoginName(loginName);
            MyRole myRole = roleService.getCodeById(registerUser.getRoleId());
            session.setAttribute(Constants.USER_SESSION_KEY, myUser);
            session.setAttribute(Constants.USER_ROLE, myRole);
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String login(String loginName, String passwordMD5, HttpSession httpSession) {
        MyUser user = myUserMapper.selectByLoginNameAndPasswd(loginName, passwordMD5);
        if (user != null && httpSession != null) {
            Date maturityTime = user.getMaturityTime();
            Byte userStatus = user.getUserStatus();
            if(maturityTime != null && userStatus.compareTo((byte)2) == 0){
                if(maturityTime.after(new Date())){
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
                    return ServiceResultEnum.BAN.getResult() + "解封时间：" + dateFormat.format(maturityTime);
                }
                else {
                    unBannedUser(user);
                }
            }
            httpSession.setAttribute(Constants.USER_SESSION_KEY, user);
            MyRole role = roleService.getCodeById(user.getRoleId());
            httpSession.setAttribute(Constants.USER_ROLE, role);
            //修改最近登录时间
            user.setLastLoginTime(new Date());
            myUserMapper.updateByPrimaryKeySelective(user);
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }

    @Override
    public Boolean updateUserInfo(MyUser myUser, HttpSession httpSession) {
        MyUser userTemp = (MyUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        MyUser userFromDB = myUserMapper.selectByPrimaryKey(userTemp.getUserId());
        //当前用户非空且状态正常才可以进行更改
        if (userFromDB != null && userFromDB.getUserStatus().intValue() == 0) {
            userFromDB.setIntroduce(SystemUtil.cleanString(myUser.getIntroduce()));
            userFromDB.setLocation(SystemUtil.cleanString(myUser.getLocation()));
            userFromDB.setGender(SystemUtil.cleanString(myUser.getGender()));
            userFromDB.setNickName(SystemUtil.cleanString(myUser.getNickName()));
            if (myUserMapper.updateByPrimaryKeySelective(userFromDB) > 0) {
                httpSession.setAttribute(Constants.USER_SESSION_KEY, userFromDB);
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean updateUserHeadImg(MyUser myUser, HttpSession httpSession) {
        MyUser userFromDB = myUserMapper.selectByPrimaryKey(myUser.getUserId());
        //当前用户非空且状态正常才可以进行更改
        if (userFromDB != null && userFromDB.getUserStatus().intValue() == 0) {
            userFromDB.setHeadImgUrl(myUser.getHeadImgUrl());
            if (myUserMapper.updateByPrimaryKeySelective(userFromDB) > 0) {
                httpSession.setAttribute(Constants.USER_SESSION_KEY, userFromDB);
                return true;
            }
        }
        return false;
    }

    @Override
    public MyUser getUserById(Long userId) {
        return myUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public Boolean updatePassword(Long userId, String originalPassword, String newPassword) {
        MyUser myUser = myUserMapper.selectByPrimaryKey(userId);
        //当前用户非空且状态正常才可以进行更改
        if (myUser != null && myUser.getUserStatus().intValue() == 0) {
            String originalPasswordMd5 = MD5Util.MD5Encode(originalPassword, "UTF-8");
            String newPasswordMd5 = MD5Util.MD5Encode(newPassword, "UTF-8");
            //比较原密码是否正确
            if (originalPasswordMd5.equals(myUser.getPasswordMd5())) {
                //设置新密码并修改
                myUser.setPasswordMd5(newPasswordMd5);
                if (myUserMapper.updateByPrimaryKeySelective(myUser) > 0) {
                    //修改成功则返回true
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int bannedUser(MyUser user, HttpSession session) {
        MyRole currentUserRole = (MyRole)session.getAttribute(Constants.USER_ROLE);
        String code = currentUserRole.getCode();
        if(code.equals(Constants.ADMIN) || code.equals(Constants.SYSADMIN) || user.getUserId() != null){
            // 封号操作
            user.setUserStatus((byte)2);
            // 封号对应的帖子
            postMapper.bannedPostByUserId(user.getUserId());
            return myUserMapper.updateByPrimaryKeySelective(user);
        }
        return 0;
    }

    @Override
    public void unBannedUser(MyUser user) {
        user.setUserStatus((byte) 0);
        // 解封用户 以及帖子
        myUserMapper.updateByIdUnseal(user);
        postMapper.unBannedPostByUserId(user.getUserId());
    }

    @Override
    public PageResult getPageBannedUser(PageQueryUtil page) {
        int counts = myUserMapper.getAllBannedUserCounts(page);
        List<MyUser> pageBannedUser = myUserMapper.getPageBannedUser(page);
        return new PageResult(pageBannedUser, counts, page.getLimit(), page.getPage());
    }

    @Override
    public List<MyUser> getSumViews() {
        return myUserMapper.getSumViews();
    }
}
